package com.eboss.sbs.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import com.eboss.sbs.R;
import com.eboss.sbs.activity.base.BaseActivity;
import com.eboss.sbs.adapter.ChooseOptionAdapter;
import com.eboss.sbs.adapter.CouponVerificationListAdapter;
import com.eboss.sbs.config.Config;
import com.eboss.sbs.enums.EnumConsts;
import com.eboss.sbs.http.API;
import com.eboss.sbs.http.HttpCallback;
import com.eboss.sbs.model.CouponNameEntity;
import com.eboss.sbs.model.CouponVerificationEntity;
import com.eboss.sbs.model.CouponVerificationListEntity;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.mytools.tool.utils.StringUtil;
import com.mytools.tool.utils.TimeUtil;
import com.mytools.tool.views.MyListView;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CouponVerificationActivity extends BaseActivity implements OnItemClickListener {

	private int TYPE_TIME_OPTION = 1;
	
	private final int REQUEST_CODE_QUERYDATE_FROM = 1;
	private final int REQUEST_CODE_QUERYDATE_TO = 2;
	
	private PullToRefreshScrollView pullToRefreshScrollView;
	
	private Date panel_dateFrom = new Date();
	private Date panel_dateTo = new Date();
	private Date query_dateFrom = panel_dateFrom;
	private Date query_dateTo = panel_dateTo;
	
	private MyListView listview;
	private CouponVerificationListAdapter adapter;
	private List<CouponVerificationEntity> datas = new ArrayList<CouponVerificationEntity>();
	//private List<CouponNameEntity> couponNames = new ArrayList<CouponNameEntity>();
	
	private int coupon_names_index = 0;
	private ArrayAdapter<String> adapter_state;
	
	private AlertDialog dialog_panel;
	
	private GridView gv_option_time;
	private ArrayList<String> time_values = new ArrayList<String>(){
		private static final long serialVersionUID = 1L;
		{
			add(EnumConsts.TimeZoneType.SEVENDAY.getName());
			add(EnumConsts.TimeZoneType.MONTH.getName());
			add(EnumConsts.TimeZoneType.MONTHLAST.getName());
			add(EnumConsts.TimeZoneType.CUSTOM.getName());
		}
	};
	private BitSet time_marks = new BitSet(4);
	private ChooseOptionAdapter adapter_time;
	private int timeType = EnumConsts.TimeZoneType.CUSTOM.getCode();
	private TextView tv_date_to, tv_date_from;
	private LinearLayout ly_time_zone;
	
	private int page = 1;
	private int rows = Config.ROWS;
	
	private Spinner spinner_coupon_name;
	//private String[] coupon_arrays_base = {"全部优惠券"};
	private List<String> coupon_names = new ArrayList<String>();
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		mActivity = this;
		setContentView(R.layout.activity_coupon_verification);
		super.onCreate(savedInstanceState);
		initView();
	}
	
	private void initView(){
		showView(R.id.titleback_btn_back, true);
		setTvText(R.id.tv_title, "优惠券核销数据  ");
		showView(R.id.next_sure, true);
		setTvText(R.id.next_sure, "筛选");
		
		String from = TimeUtil.getStringFromDate(query_dateFrom, "yyyy年MM月dd日");
		setTvText(R.id.tv_date_choose, from);
		
		coupon_names.add("全部优惠券");
		spinner_coupon_name = (Spinner) findViewById(R.id.spinner_coupon_name);
		
		adapter_state = new ArrayAdapter<String>(this, R.layout.spinner_dropdown_item, coupon_names);
		spinner_coupon_name.setAdapter(adapter_state);
		spinner_coupon_name.setSelection(0, true);
		spinner_coupon_name.setOnItemSelectedListener(new SpinnerSelectedEvent());
		
		pullToRefreshScrollView = (PullToRefreshScrollView) findViewById(R.id.pullToRefreshScrollView);
		pullToRefreshScrollView.setOnRefreshListener(new MyOnRefreshListener());
		pullToRefreshScrollView.setMode(Mode.BOTH);
		
		datas = new ArrayList<CouponVerificationEntity>();
		listview = (MyListView)findViewById(R.id.listview);
		listview.setOnItemClickListener(this);
		adapter = new CouponVerificationListAdapter(this, datas);
		
		findViewById(R.id.titleback_btn_back).setOnClickListener(this);
		findViewById(R.id.next_sure).setOnClickListener(this);
		findViewById(R.id.ly_previous).setOnClickListener(this);
		findViewById(R.id.ly_next).setOnClickListener(this);
		findViewById(R.id.ly_choose_coupon_name).setOnClickListener(this);
		
		listview.setAdapter(adapter);
		showNextDayBtn();
		
		getdata();
		
	}
	
	class SpinnerSelectedEvent implements OnItemSelectedListener{
		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			coupon_names_index = arg2;
			refreshData();
		}
		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			
		}
	}
	
	class MyOnRefreshListener implements OnRefreshListener2<ScrollView> {
		@Override
		public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
			pullToRefreshScrollView.setMode(Mode.BOTH);
			String label = DateUtils.formatDateTime(mActivity, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
			refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
			refreshData();
		}
		@Override
		public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
			page++;
			getdata();
		}
	}
	
	private void refreshData(){
		page = 1;
		getdata();
	}
	
	private void getdata(){
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("sid", mApp.getLoginEntity().getSid());
		params.put("datefrom", TimeUtil.getStringFromDate(query_dateFrom, "yyyy-MM-dd"));
		params.put("dateto", TimeUtil.getStringFromDate(query_dateTo, "yyyy-MM-dd"));
		if(coupon_names_index!=0){
			params.put("couponName", coupon_names.get(coupon_names_index));
		}
		else{
			params.put("couponName", "");
		}
		params.put("pagenum", page);
		params.put("pagesize", rows);
		
		API.http_post(this, API.COUPONUSED_LIST, params, new HttpCallback<CouponVerificationListEntity>(this) {
			@Override
			public void onSuccess(int statusCode, CouponVerificationListEntity data) {
				if(data!=null){
					if(page==1){
						datas.clear();
						setTvText(R.id.tv_num, data.getNum()+"笔");
						setTvText(R.id.tv_coupon_num, data.getTotalCouplnNum()+"张");
						setTvText(R.id.tv_cover_money, StringUtil.getMoneyString(data.getTotalCoverMoney())+"元");
						if(coupon_names_index==0){
							//reflashCouponNames(data.getCouponNames());
							List<CouponNameEntity> names = data.getCouponNames();
							int name_size = names.size()+1;
							coupon_names.clear();
							for (int i = 0; i < name_size; i++) {
								if(i==0){coupon_names.add("全部优惠券");}
								else{
									coupon_names.add(names.get(i-1).getCouponName());
								}
							}
							adapter_state.notifyDataSetChanged();
						}
					}
					List<CouponVerificationEntity> tmp_datas = data.getConsumptions();
					 if(tmp_datas==null||tmp_datas.size()==0||tmp_datas.size()<rows){
						if(tmp_datas==null||tmp_datas.size()==0){
							toast("没有更多数据");
						}
						pullToRefreshScrollView.setMode(Mode.PULL_DOWN_TO_REFRESH);
					 }
					 if(tmp_datas!=null&&tmp_datas.size()>0){
						 datas.addAll(tmp_datas);
					 }
				}
				adapter.notifyDataSetChanged();
				pullToRefreshScrollView.onRefreshComplete();
			}
			
			@Override
			public void onFailure(int code, String message) {
				pullToRefreshScrollView.onRefreshComplete();
				super.onFailure(code, message);
			}
			
			@SuppressWarnings({ "unchecked", "rawtypes" })
			@Override
			public TypeToken getTypeToken() {
				return new TypeToken<CouponVerificationListEntity>() {
				};
			}
		});
		
	}
	
	@Override
	public void onClick(View v) {
		Intent intent = new Intent();
		switch (v.getId()) {
			case R.id.titleback_btn_back:
				finish();
				break;
			case R.id.next_sure:
				showPanel();
				break;
			case R.id.ly_previous:
				query_dateFrom = TimeUtil.getDateFromDate(query_dateFrom, -1);
				query_dateTo = query_dateFrom;
				panel_dateFrom = query_dateFrom;
				panel_dateTo = query_dateTo;
				timeType = EnumConsts.TimeZoneType.CUSTOM.getCode();
				coupon_names_index = 0;
				setTvText(R.id.tv_date_choose, TimeUtil.getStringFromDate(query_dateFrom, "yyyy年MM月dd日"));
				showNextDayBtn();
				refreshData();
				break;
			case R.id.ly_next:
				query_dateFrom = TimeUtil.getDateFromDate(query_dateFrom, 1);
				query_dateTo = query_dateFrom;
				panel_dateFrom = query_dateFrom;
				panel_dateTo = query_dateTo;
				timeType = EnumConsts.TimeZoneType.CUSTOM.getCode();
				coupon_names_index = 0;
				setTvText(R.id.tv_date_choose, TimeUtil.getStringFromDate(query_dateFrom, "yyyy年MM月dd日"));
				showNextDayBtn();
				refreshData();
				break;
			case R.id.tv_date_from:
				intent.setClass(mActivity, ChooseDateActivity.class);
				String tmp_date_str_from = TimeUtil.getStringFromDate(panel_dateFrom==null?(new Date()):panel_dateFrom, ChooseDateActivity.FORMAT_DATE);
				intent.putExtra(ChooseDateActivity.PARA_SELECTED_DATE, tmp_date_str_from);
				intent.putExtra("chooseType", ChooseDateActivity.CHOOSE_BEFORE_TODAY);
				intent.putExtra("toDate", TimeUtil.getStringFromDate(panel_dateTo, ChooseDateActivity.FORMAT_DATE));
				startActivityForResult(intent, REQUEST_CODE_QUERYDATE_FROM);
				break;
			case R.id.tv_date_to:
				intent.setClass(mActivity, ChooseDateActivity.class);
				String tmp_date_str_to = TimeUtil.getStringFromDate(panel_dateTo==null?(new Date()):panel_dateTo, ChooseDateActivity.FORMAT_DATE);
				intent.putExtra(ChooseDateActivity.PARA_SELECTED_DATE, tmp_date_str_to);
				intent.putExtra("chooseType", ChooseDateActivity.CHOOSE_BEFORE_TODAY);
				intent.putExtra("fromDate", TimeUtil.getStringFromDate(panel_dateFrom, ChooseDateActivity.FORMAT_DATE));
				startActivityForResult(intent, REQUEST_CODE_QUERYDATE_TO);
				break;
			case R.id.btn_filter_confirm:
				
				if(dialog_panel!=null){dialog_panel.dismiss();}
				
				if(timeType== EnumConsts.TimeZoneType.CUSTOM.getCode()){
					query_dateFrom = panel_dateFrom;
					query_dateTo = panel_dateTo;
				}
				else{
					Date today = new Date();
					if(timeType== EnumConsts.TimeZoneType.SEVENDAY.getCode()){
						query_dateFrom = TimeUtil.getDateFromDate(today, -7);
						query_dateTo = TimeUtil.getDateFromDate(today, -1);
					}
					else if(timeType== EnumConsts.TimeZoneType.MONTH.getCode()){
						query_dateFrom = TimeUtil.getDateFromString(TimeUtil.getCurrentDateString("yyyyMM")+"01", "yyyyMMdd");
						query_dateTo = TimeUtil.getDateFromDate(today, 0);
					}
					else if(timeType== EnumConsts.TimeZoneType.MONTHLAST.getCode()){
						Date query_dateTo_tmp = TimeUtil.getDateFromString(TimeUtil.getCurrentDateString("yyyyMM")+"01", "yyyyMMdd");
						query_dateTo = TimeUtil.getDateFromDate(query_dateTo_tmp, -1);
						query_dateFrom = TimeUtil.getDateFromString(TimeUtil.getStringFromDate(query_dateTo, "yyyyMM")+"01", "yyyyMMdd");
					}
				}
				coupon_names_index = 0; //不带优惠券名称选择条件
				panel_dateFrom = query_dateFrom;
				panel_dateTo = query_dateTo;
				String from = TimeUtil.getStringFromDate(query_dateFrom, "yyyy年MM月dd日");
				String to = TimeUtil.getStringFromDate(query_dateTo, "yyyy年MM月dd日");
				boolean checkshow = from.equals(to);
				showView(R.id.ly_date_chooser, checkshow?true:false);
				showView(R.id.ly_date_show, checkshow?false:true);
				setTvText(R.id.tv_date_choose, from);
				setTvText(R.id.tv_date_show, from+" - "+to);
				
				showNextDayBtn();
				refreshData();
				
				break;
			default:break;
		}
		super.onClick(v);
	}
	
	private void showPanel() {
		dialog_panel = new AlertDialog.Builder(mActivity).create();
		dialog_panel.show();
		Window window = dialog_panel.getWindow();
		
		WindowManager.LayoutParams lp =window.getAttributes();
		lp.x=0;
		lp.y=150;
		
		// 设置布局
		window.setContentView(R.layout.dialog_consumption_filter);
		// 设置宽高
		window.setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		// 设置弹出的动画效果
		//window.setWindowAnimations(R.style.DialogAnimTop);
		// show at bottom
		window.setGravity(Gravity.TOP); 
		
		ly_time_zone = (LinearLayout) window.findViewById(R.id.ly_time_zone);
		tv_date_from = (TextView) window.findViewById(R.id.tv_date_from);
		tv_date_to = (TextView) window.findViewById(R.id.tv_date_to);
		tv_date_from.setOnClickListener(this);
		tv_date_to.setOnClickListener(this);
		
		window.findViewById(R.id.btn_filter_confirm).setOnClickListener(this);
		
		gv_option_time = (GridView) window.findViewById(R.id.gv_option_time);
		adapter_time = new ChooseOptionAdapter(mActivity, time_values, time_marks);
		gv_option_time.setAdapter(adapter_time);
		gv_option_time.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				adapterNotify(TYPE_TIME_OPTION, arg2);
			}
		});
		
		reflashPanel();
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode!=RESULT_OK)return;
		switch (requestCode) {
			case REQUEST_CODE_QUERYDATE_FROM:
				String a = data.getStringExtra(ChooseDateActivity.PARA_SELECTED_DATE);
				panel_dateFrom = TimeUtil.getDateFromString(a, ChooseDateActivity.FORMAT_DATE);
				tv_date_from.setText(TimeUtil.getStringFromDate(panel_dateFrom, "yyyy年MM月dd日"));
				break;
			case REQUEST_CODE_QUERYDATE_TO:
				String b = data.getStringExtra(ChooseDateActivity.PARA_SELECTED_DATE);
				panel_dateTo = TimeUtil.getDateFromString(b, ChooseDateActivity.FORMAT_DATE);
				tv_date_to.setText(TimeUtil.getStringFromDate(panel_dateTo, "yyyy年MM月dd日"));
				break;
			default: break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	private void adapterNotify(int adapterType, int index){
		if(adapterType==TYPE_TIME_OPTION){
			timeType = EnumConsts.TimeZoneType.getCodeByName(time_values.get(index));
			reflashPanel();
		}
	}
	
	private void reflashPanel(){
		int size = time_values.size();
		for (int i = 0; i < size; i++) {
			int type_tmp = EnumConsts.TimeZoneType.getCodeByName(time_values.get(i));
			time_marks.set(i, type_tmp==timeType?true:false);
		}
		ly_time_zone.setVisibility(timeType== EnumConsts.TimeZoneType.CUSTOM.getCode()?View.VISIBLE:View.GONE);
		if(timeType== EnumConsts.TimeZoneType.CUSTOM.getCode()){
			tv_date_from.setText(TimeUtil.getStringFromDate(panel_dateFrom, "yyyy年MM月dd日"));
			tv_date_to.setText(TimeUtil.getStringFromDate(panel_dateTo, "yyyy年MM月dd日"));
		}
		
		adapter_time.notifyDataSetChanged();
	}
	
	private void showNextDayBtn(){
		String a = TimeUtil.getStringFromDate(query_dateFrom, "yyyyMMdd");
		String b = TimeUtil.getStringFromDate(query_dateTo, "yyyyMMdd");
		String c = TimeUtil.getCurrentDateString("yyyyMMdd");
		showView(R.id.ly_next, !(a.equals(b)&&b.equals(c)));
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Intent intent = new Intent();
		intent.setClass(mActivity, TradeDetailActivity.class);
		intent.putExtra("tradeOrderNo", datas.get(position).getTradeOrderNo());
		startActivity(intent);
	}
	
}
